package com.ruoyi.system.config;

import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.ruoyi.system.service.IPCabinetService;
import com.ruoyi.system.service.IPTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class DeviceHeartbeatTask {

    private static final Logger log = LoggerFactory.getLogger(DeviceHeartbeatTask.class);

    @Autowired
    private IPCabinetService pcabinetService;
    @Autowired
    private IPTaskService taskService;

    /**
     * 获取Hutool线程池实例
     */
    private ExecutorService getTaskExecutor() {
        // 使用静态变量缓存线程池实例
        if (taskExecutor == null) {
            synchronized (this.getClass()) {
                if (taskExecutor == null) {
                    // 构建一个固定大小的线程池
                    taskExecutor = ExecutorBuilder.create()
                            .setCorePoolSize(5)           // 核心线程数
                            .setMaxPoolSize(20)           // 最大线程数
                            .setKeepAliveTime(30)         // 线程空闲时间(秒)
                            .setWorkQueue(new LinkedBlockingQueue<>(100)) // 队列大小
                            .setThreadFactory(ThreadFactoryBuilder.create()
                                    .setNamePrefix("expire-task-")  // 线程名前缀
                                    .setDaemon(true)               // 设置为守护线程
                                    .build())
                            .build();
                }
            }
        }
        return taskExecutor;
    }

    private static ExecutorService taskExecutor;

    /**
     * 每30秒执行一次心跳检测
     */
//    @Scheduled(fixedRate = 30000)
//    public void heartbeatTask() {
//        log.info("开始执行设备心跳检测任务");
//        try {
//            pcabinetService.sendHeartbeatToAllDevices();
//        } catch (Exception e) {
//            log.error("心跳检测任务执行异常: {}", e.getMessage(), e);
//        }
//        log.info("设备心跳检测任务执行完成");
//    }

    //@Scheduled(fixedRateString =  "#{${ruoyi.dyPassExpire} * 60000}")
    @Scheduled(fixedRate =  60000)
    public void heartbeatTask() {
        log.info("开始扫描密码是否过期");

        // 使用Hutool创建的线程池执行任务
        getTaskExecutor().submit(() -> {
            try {
                taskService.scanUpdateTaskStatus();
            } catch (Exception e) {
                log.error("扫描密码过期任务执行异常: {}", e.getMessage(), e);
            }
        });

        log.info("扫描密码过期任务已提交异步执行");
    }
}